package com.fms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fms.constant.PhotoType;
import com.fms.dto.SignPhotoDto;
import com.fms.entity.PhotoInfo;
import com.fms.mapper.PhotoInfoMapper;
import com.fms.result.ResultData;
import com.fms.service.PhotoInfoService;
import com.fms.util.AliOSSUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
@RequiredArgsConstructor
public class PhotoInfoServiceImpl extends ServiceImpl<PhotoInfoMapper, PhotoInfo> implements PhotoInfoService {
    private final AliOSSUtils aliOSSUtils;

    private final PhotoInfoMapper photoInfoMapper;
    @Override
    public ResultData deleteContractPhoto(String contractPhotoUrl) {
        String decodedUrl = null;
        try {
            decodedUrl = URLDecoder.decode(contractPhotoUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        while (decodedUrl.endsWith("=")) {
            decodedUrl = decodedUrl.substring(0, decodedUrl.length() - 1);
        }
        System.out.println(decodedUrl);
        LambdaQueryWrapper<PhotoInfo> photoWrapper = new LambdaQueryWrapper<PhotoInfo>();
        photoWrapper.eq(PhotoInfo::getPhotoUrl, decodedUrl);
        photoInfoMapper.delete(photoWrapper);
        return ResultData.success("图片删除成功");
    }

    //增加签字图片
    @Override
    public ResultData addSignPhoto(SignPhotoDto signPhotoDto) throws IOException {
        String base64Data = signPhotoDto.getUrl();
        // 提取base64数据
        final String[] base64Array = base64Data.split(",");
        String dataUir, data;
        if (base64Array.length > 1) {
            dataUir = base64Array[0];
            data = base64Array[1];
        } else {
            //根据你base64代表的具体文件构建
            dataUir = "data:image/jpg;base64";
            data = base64Array[0];
        }
        MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
        String uploadUrl = aliOSSUtils.upload(multipartFile);
        PhotoInfo photoInfo = new PhotoInfo();
        photoInfo.setPhotoUrl(uploadUrl);
        photoInfo.setPhotoType(PhotoType.SignPhoto);
        photoInfo.setOrderId(signPhotoDto.getOrderId());
        photoInfoMapper.insert(photoInfo);
        return ResultData.success("签字文件保存成功",uploadUrl);
    }

    public static class Base64ToMultipartFile implements MultipartFile {
        private final byte[] fileContent;

        private final String extension;
        private final String contentType;


        /**
         * @param base64
         * @param dataUri     格式类似于: data:image/png;base64
         */
        public Base64ToMultipartFile(String base64, String dataUri) {
            this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
            this.extension = dataUri.split(";")[0].split("/")[1];
            this.contentType = dataUri.split(";")[0].split(":")[1];
        }

        public Base64ToMultipartFile(String base64, String extension, String contentType) {
            this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
            this.extension = extension;
            this.contentType = contentType;
        }

        @Override
        public String getName() {
            return "param_" + System.currentTimeMillis();
        }

        @Override
        public String getOriginalFilename() {
            return "file_" + System.currentTimeMillis() + "." + extension;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return fileContent == null || fileContent.length == 0;
        }

        @Override
        public long getSize() {
            return fileContent.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return fileContent;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(fileContent);
        }

        @Override
        public void transferTo(File file) throws IOException, IllegalStateException {
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(fileContent);
            }
        }

    }
}
